<?php

/**
 * 课程 API
 * User: don
 */

namespace app\modules\app\controllers;

use app\modules\app\models\IntegralBuy;
use app\modules\app\models\UserPlan;
use app\modules\content\models\IeltsSpeak;
use yii;
use app\libs\AppControl;
use app\libs\Method;
use app\modules\content\models\Classes;
use app\modules\content\models\ClassesSdk;
use app\modules\content\models\VideoLog;

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: X-Requested-With');
header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');

class UcenterController extends AppControl
{

    public $enableCsrfValidation = false;

    function init (){
        parent::init();
        include_once($_SERVER['DOCUMENT_ROOT'].'/../libs/ucenter/ucenter.php');
    }

    /**
     * [actionCourse description]
     * @Author don
     * @Date   2021-11-03
     * @return [type]     [description]
     */
    public function actionCourse()
    {
        $uid = Yii::$app->session->get('uid');
        // $uid=3;
        if (!$uid) {
            die(json_encode(['code'=>5, 'message'=>'未登录！']));
        }

        $type = Yii::$app->request->post('type', 1);  // 类型1公开课2试听课
        $page = Yii::$app->request->post('page', 1);
        $pageSize = Yii::$app->request->post('pageSize', 10);
        
        if ($type == 1) {
            $limit = " limit ".($page-1) * $pageSize . ", $pageSize";
            $sql = "select b.id,b.name,b.teacher,b.course_image,b.course_tag,a.id as logId,a.record,a.sort from x2_user_video_log a left join x2_classes b on a.classesId=b.id where a.updateTime in (select MAX(updateTime) as newTime from x2_user_video_log where uid=$uid and type=1 group by classesId) order by a.updateTime desc $limit";
            $count = "select b.id,b.name,b.teacher,b.course_image,b.course_tag,a.id as logId,a.record,a.sort from x2_user_video_log a left join x2_classes b on a.classesId=b.id where a.updateTime in (select MAX(updateTime) as newTime from x2_user_video_log where uid=$uid and type=1 group by classesId) order by a.updateTime desc";
            
            // // $sql = "select b.id,b.name,b.teacher,b.course_image,b.course_tag,a.id as logId,a.record,a.sort from x2_user_video_log a left join x2_classes b on a.classesId=b.id where a.uid=$uid and a.type=1 order by a.updateTime desc $limit";
            // $sql = "select r.id,r.name,r.teacher,r.course_image,r.course_tag,r.logId,r.record,r.sort from (select b.id,b.name,b.teacher,b.course_image,b.course_tag,a.id as logId,a.record,a.sort from x2_user_video_log a left join x2_classes b on a.classesId=b.id where a.uid=$uid and a.type=1 order by a.updateTime desc $limit) r group by r.id";
            // // $count = "select b.id,b.name,b.teacher,b.course_image,b.course_tag,a.id as logId,a.record,a.sort from x2_user_video_log a left join x2_classes b on a.classesId=b.id where a.uid=$uid and a.type=1 order by a.updateTime desc";
            // $count = "select r.id,r.name,r.teacher,r.course_image,r.course_tag,r.logId,r.record,r.sort from (select b.id,b.name,b.teacher,b.course_image,b.course_tag,a.id as logId,a.record,a.sort from x2_user_video_log a left join x2_classes b on a.classesId=b.id where a.uid=$uid and a.type=1 order by a.updateTime desc) r group by r.id";
            $data = Yii::$app->db->createCommand($sql)->queryAll();
            $count = count(Yii::$app->db->createCommand($count)->queryAll());
            $countPage = ceil($count / $pageSize);

        } elseif ($type == 2) {

            $offset = $pageSize * ($page - 1);
            $data = VideoLog::find()->select('x2_teachers.id,x2_teachers.course_title as name,x2_teachers.name as teacher,x2_user_video_log.id as logId,x2_user_video_log.record,x2_user_video_log.sort,x2_teachers.url as sdk')->where(['x2_user_video_log.type'=>2, 'x2_user_video_log.uid'=>$uid])->leftJoin('x2_teachers', 'x2_user_video_log.classesId=x2_teachers.id')->offset($offset)->orderBy('x2_user_video_log.id desc')->limit($pageSize)->asArray()->all();
            $count = VideoLog::find()->where(['uid'=>$uid, 'type'=>2])->count();
            $countPage = ceil($count / $pageSize);
        }
        if ($data) { // 处理时间格式
            foreach ($data as $key => $value) {
                if ($type == 1) {
                    $data[$key]['course_tag'] = $value['course_tag']?explode(',', $value['course_tag']):null;
                }
                $data[$key]['record'] = gmstrftime('%H:%M:%S', $value['record']);
                // 处理封面图
                $data[$key]['course_image'] = $value['course_image']?"https://www.thinkuprep.com".$value['course_image']:null;
            }
        }

        die(json_encode(['code'=>1, 'data'=>$data, 'page'=>$page, 'countPage'=>$countPage]));
    }

    /**
     * [actionDeleteVideoRecord 删除课程视频观看记录]
     * @Author don
     * @Date   2021-11-04
     * @return [type]     [description]
     */
    public function actionDeleteVideoRecord()
    {
        $logId = Yii::$app->request->post('logId');  // 记录id和英文逗号组成的字符串
        $logId = explode(',',$logId);
        // $res = VideoLog::deleteAll(['id' => $logId]);
        $res = VideoLog::deleteAll(['in', 'id', $logId]);
        if (!$res) {
            die(json_encode(['code'=>0, 'message'=>'删除失败！']));
        }

        die(json_encode(['code'=>1, 'message'=>'删除成功！']));
    }

    /**
     * 我的课程
     */
    public function actionMyCourse(){
        $uid = Yii::$app->session->get('uid');
        if (!$uid) {
            die(json_encode(['code'=>5, 'message'=>'未登录！']));
        }
        $type = Yii::$app->request->get('type');
        $page = Yii::$app->request->get('page',1);
        $where = " (uo.orderBelong=8 or uo.orderBelong=12)";
        if ($type == 1) {
            $where .= ' and uo.order_form=1 ';
        } elseif ($type == 2) {
            $where .= ' and (uo.order_form is null or uo.order_form=2) ';
        }
        $data = Method::curl_post_fix(Yii::$app->params['thinkuOrderUrl']."/pay/api/class",['where' => $where,'pageSize' => 10,'page' => $page,'uid'=>$uid]);
        $data = json_decode($data,true);
        if(isset($data['pageStr'])) unset($data['pageStr']);
        $data = Classes::getOrderInfo($data);
        die(json_encode(['code'=>1, 'message'=>'success','data'=>$data]));
    }

    /**
     * 我的订单
     */
    public function actionMyOrder(){
        $uid = Yii::$app->session->get('uid');
        if (!$uid) {
            die(json_encode(['code'=>5, 'message'=>'未登录！']));
        }
        $status = Yii::$app->request->get('status');
        $page = Yii::$app->request->get('page',1);
        if(!$status) $status = 9;
        $where = " (uo.orderBelong=8 or uo.orderBelong=12)";

        $data = Method::curl_post_fix(Yii::$app->params['thinkuOrderUrl']."/pay/api/class",['where' => $where,'pageSize' => 10,'page' => $page,'uid'=>$uid,'status'=>$status]);
        $data = json_decode($data,true);
        if(isset($data['pageStr'])) unset($data['pageStr']);
        $data = Classes::getOrderInfo($data,0);
        die(json_encode(['code'=>1, 'message'=>'success','data'=>$data]));
    }

    /**
     * 订单详情
     */
    public function actionOrderDetail(){
        $uid = Yii::$app->session->get('uid');
        if (!$uid) {
            die(json_encode(['code'=>5, 'message'=>'未登录！']));
        }
        $orderId = Yii::$app->request->get('orderId');
        $where = ' (uo.orderBelong=8 or uo.orderBelong=12) and uo.id='.$orderId;
        $data = Method::curl_post_fix(Yii::$app->params['thinkuOrderUrl']."/pay/api/class",['where' => $where,'pageSize' => 1,'page' => 1,'uid'=>$uid,'status'=>9]);
        $data = json_decode($data,true);
        if(!empty($data['data'][0])){
            $data = Classes::details($data['data'][0]);
            die(json_encode(['code'=>1, 'message'=>'success','data'=>$data]));
        }else{
            die(json_encode(['code'=>0, 'message'=>'数据获取失败']));
        }
    }

    /**
     * 消息--点赞
     */
    public function actionLikeList(){
        $uid = Yii::$app->session->get('uid');
        if (!$uid) {
            die(json_encode(['code'=>5, 'message'=>'未登录！']));
        }
        $page = Yii::$app->request->get('page',1);
        $pageSize = Yii::$app->request->get('pageSize',10);
        $data = IeltsSpeak::userLikeData($uid,$page,$pageSize);
        die(json_encode(['code'=>1, 'message'=>'success','data'=>$data]));
    }

    /**
     * 消息--点赞数
     */
    public function actionLikeCount(){
        $uid = Yii::$app->session->get('uid');
        $data = IeltsSpeak::userLikeNum($uid);
        die(json_encode(['code'=>1, 'message'=>'success','data'=>$data]));
    }

    /**
     * 一键已读
     */
    public function actionReadAll(){
        $uid = Yii::$app->session->get('uid');
        if (!$uid) {
            die(json_encode(['code'=>5, 'message'=>'未登录！']));
        }
        IeltsSpeak::changeStatus($uid);
        die(json_encode(['code'=>1, 'message'=>'success']));
    }

    /**
     * 蜜糖记录
     */
    public function actionIntegralRecord(){
        $uid = Yii::$app->session->get('uid');
        $type = Yii::$app->request->get('type',1);
        $page = Yii::$app->request->get('page',1);
        $pageSize = Yii::$app->request->get('pageSize',10);
        if (!$uid) {
            die(json_encode(['code'=>5, 'message'=>'未登录！']));
        }
        $data = IntegralBuy::record($uid,$type,$page,$pageSize);
        $user = uc_user_integral1($uid);
        die(json_encode(['code'=>1, 'message'=>'success','data'=>['list'=>$data,'integral'=>$user['integral']]]));
    }

    /**
     * 学习课表
     * yoyo
     */
    public function actionTimetable(){
        $user = Yii::$app->session->get("userData");
        if($user==false){
            die(json_encode(['code'=>99,'data'=>'','message'=>'请登录']));
        }
        $id = json_decode(file_get_contents("https://api-crm.viplgw.cn/content/api/get-student-id-by-account?account={$user['uid']}&phone={$user['phone']}&email={$user['email']}"),true)['id'];
//        $id=65518;
        $content = $id != false ? json_decode(file_get_contents("https://course.viplgw.cn/cn/external-api/get-class?clientId=$id&belong=24"), true) : array();
        $date = array_unique(array_column($content, 'date'));
        static $data = array();
        foreach ($content as $key => $val) {
            $n = array_search($val['date'], $date);
            if ($n !== false) {
                $data[$n]['date'] = $val['date'];
                $data[$n]['course'][] = $val;
            }
        }
        $data=array_values($data);
        die(json_encode(['code'=>1, 'message'=>'success','data'=>$data]));
    }

    /**
     * 学习计划
     * yoyo
     */
    public function actionPlan()
    {
        $uid = Yii::$app->session->get("uid");
        if ($uid == false) {
            die(json_encode(['code' => 99, 'data' => '', 'message' => '请登录']));
        }
        $model = new UserPlan();
        $model->place = Yii::$app->request->post('place');
        $model->uid = $uid;
        $model->target = Yii::$app->request->post('target');
        $model->testTime = Yii::$app->request->post('tetsTime');
        $model->status = Yii::$app->request->post('status');
        $model->career = Yii::$app->request->post('career');
        $model->applyTime = Yii::$app->request->post('applyTime');
        $model->score = Yii::$app->request->post('score');
        $model->createTime = time();
        if ($model->save()) {
            die(json_encode(['code' => 1, 'message' => 'success']));
        } else {
            die(json_encode(['code' => 0, 'message' => 'fail']));
        }
    }
}
